package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.repository.*;
import com.hualude.roadsign.service.SolarService;
import com.hualude.roadsign.utils.PushUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by pjn on 2017/7/11.
 */
@Service
public class SolarServiceImpl implements SolarService {

    @Resource
    private SolarFaultRepository solarFaultRepository;

    @Resource
    private SolarEnergyRepository solarEnergyRepository;

    @Resource
    private UserRepository userRepository;

    @Resource
    private OrgRepository orgRepository;

    @Resource
    private PushHistoryRepository pushHistoryRepository;

    private String strUserIds;

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public DTResponseDto getSolarFault4DT(DTRequestDto dtRequestDto, Integer actorId, Integer userId, Integer orgId) throws Exception {
        Integer count;
        List<DTSolarFaultDto> dto4DTs;
        count = solarFaultRepository.getSolarFaultCount4DT(actorId, userId, orgId, dtRequestDto.getSearch());
        dto4DTs = solarFaultRepository.getSolarFault4DT(dtRequestDto, actorId, userId, orgId);
        for (DTSolarFaultDto dto : dto4DTs) {
            dto.setSolarCheckerName(userRepository.getUserNameByUserId(dto.getSolarCheckerId()));
        }
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        return dtResponseDto;
    }

    public SolarEnergyFaultDto getSolarEnergyInfo2Fault(Integer solarEnergyId) throws Exception {
        SolarEnergyFaultDto solarEnergyFaultDto;
        solarEnergyFaultDto = solarEnergyRepository.getSolarEnergyInfo2Fault(solarEnergyId);
        solarEnergyFaultDto.setSolarEnergyCreatorName(userRepository.getUserNameByUserId(solarEnergyFaultDto.getSolarEnergyCreatorId()));
        solarEnergyFaultDto.setSolarEnergyOrgName(orgRepository.getMainOrgName(solarEnergyFaultDto.getSolarEnergyOrgId()));
        solarEnergyFaultDto.setSolarEnergyMainOrgName(orgRepository.getMainOrgName(solarEnergyFaultDto.getSolarEnergyMainOrgId()));
        solarEnergyFaultDto.setSolarEnergyId(solarEnergyId);
        return solarEnergyFaultDto;
    }

    public SolarEnergyFaultDto getSolarFaultInfo2Fault(Integer solarEnergyId, Integer solarFaultId) throws Exception {
        SolarEnergyFaultDto solarEnergyFaultDto;
        solarEnergyFaultDto = solarEnergyRepository.getSolarEnergyInfo2Fault(solarEnergyId);
        SolarEnergyFaultDto solarFault = solarFaultRepository.getSolarFaultInfo2Fault(solarFaultId);
        solarFault.setSolarEnergyProvince(solarEnergyFaultDto.getSolarEnergyProvince());
        solarFault.setSolarEnergyCity(solarEnergyFaultDto.getSolarEnergyCity());
        solarFault.setSolarEnergyArea(solarEnergyFaultDto.getSolarEnergyArea());
        solarFault.setSolarEnergyRoadName(solarEnergyFaultDto.getSolarEnergyRoadName());
        solarFault.setSolarEnergyStartRoad(solarEnergyFaultDto.getSolarEnergyStartRoad());
        solarFault.setSolarEnergyEndRoad(solarEnergyFaultDto.getSolarEnergyEndRoad());
        solarFault.setSolarEnergyLongitude(solarEnergyFaultDto.getSolarEnergyLongitude());
        solarFault.setSolarEnergyLatitude(solarEnergyFaultDto.getSolarEnergyLatitude());
        solarFault.setSolarOrgId(solarEnergyFaultDto.getSolarEnergyOrgId());
        solarFault.setSolarMainOrgId(solarEnergyFaultDto.getSolarEnergyMainOrgId());
        solarFault.setSolarCreatorName(userRepository.getUserNameByUserId(solarFault.getSolarCreatorId()));
        solarFault.setSolarCreatorPhone(userRepository.getUserById(solarFault.getSolarCreatorId()).getUserMobile());
        return solarFault;
    }

    @Transactional
    public Integer solarFaultAudit(Integer isPass, String solarFeedback, Integer solarFaultId, Integer solarCheckerId) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Integer result = solarFaultRepository.solarFaultAudit(isPass, solarFeedback, solarFaultId, solarCheckerId, df.format(new Date()));
        //System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        if (isPass == 1) {
            final SolarEnergyFaultDto faultDto = solarFaultRepository.getInfoByFaultId(solarFaultId);
            List<UserDto> userDtos = userRepository.getUserIdsByOrgIdAndActorId(faultDto.getSolarMainOrgId(), 7);
            final String msg = "太阳能 NO：" + faultDto.getSolarEnergyId() + " 待审核";
            strUserIds = "";
            for (UserDto userDto : userDtos) {
                strUserIds += userDto.getUserId().toString() + ",";
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (!strUserIds.equals("")) {
                            strUserIds = strUserIds.substring(0, strUserIds.length() - 1);
                            PushUtil.sendPushToUser(strUserIds, msg);
                            PushHistoryDto pushHistoryDto = new PushHistoryDto(faultDto.getSolarMainOrgId(), 7, msg, formatter.format(new Date()),4);
                            pushHistoryRepository.save(pushHistoryDto.toBean());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        return result;
    }

    @Transactional
    public Integer deleteSolarFaultByIds(String solarFaultIds) throws Exception {
        String[] solarFaultIdArray = solarFaultIds.split(",");
        int i = 0;
        for (i = 0; i < solarFaultIdArray.length; i++) {
            solarFaultRepository.deleteSolarFaultByIds(Integer.parseInt(solarFaultIdArray[i]));
        }
        return i;
    }

    public DTResponseDto getSolarFaultReport4DT(DTRequestDto dtRequestDto, Integer actorId, Integer orgId, String solarEnergyStartRoad, String solarEnergyEndRoad, String solarEnergyRoadName) throws Exception {
        if (solarEnergyStartRoad.equals("") && solarEnergyEndRoad.equals("") && solarEnergyRoadName.equals("")) {
            return new DTResponseDto(dtRequestDto.getDraw(), 0, 0, "");
        } else {
            Integer count = solarFaultRepository.getSolarFaultReportCount4DT(dtRequestDto.getSearch(), actorId, orgId, solarEnergyStartRoad, solarEnergyEndRoad, solarEnergyRoadName);
            List<DTSolarFaultDto> dto4DTs = solarFaultRepository.getSolarFaultReport4DT(dtRequestDto, actorId, orgId, solarEnergyStartRoad, solarEnergyEndRoad, solarEnergyRoadName);
            for (DTSolarFaultDto dto : dto4DTs) {
                List<SolarEnergyFaultDto> solarEnergyFaultDto = solarEnergyRepository.getFaultIsReport(dto.getSolarEnergyId());
                Integer result = 1;
                if (solarEnergyFaultDto.size() != 0) {
                    Integer mainCheck = solarEnergyFaultDto.get(0).getSolarMainCheck();
                    Integer check = solarEnergyFaultDto.get(0).getSolarCheck();
                    Integer status = solarEnergyFaultDto.get(0).getSolarMaintenanceStatus();
                    if (status == 2) {
                        result = 1;//维修完成
                    } else if (mainCheck == -1 || check == -1) {
                        result = 1;//
                    } else {
                        result = 0;
                    }
                }
                dto.setReportStatus(result);
            }
            DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
            return dtResponseDto;
        }
    }

    public List<String> getRoadByRoadName(String roadName, Integer actorId, Integer orgId) throws Exception {
        return solarEnergyRepository.getRoadByRoadName(roadName, actorId, orgId);
    }

    @Override
    public List<String> getSectionByRoadName(String roadName, Integer actorId, Integer orgId) throws Exception {
        return solarEnergyRepository.getSectionByRoadName(roadName, actorId, orgId);
    }

    @Transactional
    public Integer updateSolarFault(Integer solarFaultId, Integer solarLevel, Integer solarType, String solarPhoto, String solarReason, Double solarMoney) throws Exception {
        return solarFaultRepository.updateSolarFault(solarFaultId, solarLevel, solarType, solarPhoto, solarReason, solarMoney);
    }

    public List<SolarEnergyFaultDto> getSolarCoordinate4Map(Integer orgId, Integer actorId) throws Exception {
        return solarEnergyRepository.getSolarCoordinate4Map(orgId, actorId);
    }

    public List<SolarEnergyFaultDto> getSolarEnergyByXY(String longitude, String latitude) throws Exception {
        return solarEnergyRepository.getSolarEnergyByXY(longitude, latitude);
    }

    @Transactional
    public Integer getFaultIsReport(Integer solarEnergyId) throws Exception {
        List<SolarEnergyFaultDto> solarEnergyFaultDto = solarEnergyRepository.getFaultIsReport(solarEnergyId);
        Integer result = 1;
        if (solarEnergyFaultDto.size() != 0) {
            Integer mainCheck = solarEnergyFaultDto.get(0).getSolarMainCheck();
            Integer check = solarEnergyFaultDto.get(0).getSolarCheck();
            Integer status = solarEnergyFaultDto.get(0).getSolarMaintenanceStatus();
            if (status == 2) {
                result = 1;//维修完成
            } else if (mainCheck == -1 || check == -1) {
                result = 1;//
            } else {
                result = 0;
            }
        }
        return result;
    }

    public Integer reportSolarFault(final Integer solarEnergyId, Integer solarCreatorId, Integer solarLevel, Integer solarType,
                                    String solarPhoto, String solarReason, Double solarMoney, final Integer solarOrgId, Integer solarMainOrgId) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        if (solarMoney == null)
            solarMoney = 0.0;
        SolarEnergyFaultDto insertDto = new SolarEnergyFaultDto();
        insertDto.setSolarEnergyId(solarEnergyId);
        insertDto.setSolarOrgId(solarOrgId);
        insertDto.setSolarMainOrgId(solarMainOrgId);
        insertDto.setSolarTime(df.format(new Date()));
        insertDto.setSolarCreatorId(solarCreatorId);
        insertDto.setSolarLevel(solarLevel);
        insertDto.setSolarPhoto(solarPhoto);
        insertDto.setSolarType(solarType);
        insertDto.setSolarReason(solarReason);
        insertDto.setSolarMoney(solarMoney);

        List<UserDto> userDtos = userRepository.getUserIdsByOrgIdAndActorId(solarOrgId, 3);
        final String msg = "太阳能 NO：" + solarEnergyId + " 待审核";
        strUserIds = "";
        for (UserDto userDto : userDtos) {
            strUserIds += userDto.getUserId().toString() + ",";
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!strUserIds.equals("")) {
                        strUserIds = strUserIds.substring(0, strUserIds.length() - 1);
                        PushUtil.sendPushToUser(strUserIds, msg);
                        PushHistoryDto pushHistoryDto = new PushHistoryDto(solarOrgId, 3, msg, formatter.format(new Date()),4);
                        pushHistoryRepository.save(pushHistoryDto.toBean());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return solarFaultRepository.save(insertDto.toBean()).getSolarEnergyId();
    }

    public List<SolarEnergyFaultDto> getSolarFaultList4App(Integer orgId, String actorIds, Integer faultStatus, Integer count, Integer size) throws Exception {
        return solarFaultRepository.getSolarFaultList4App(orgId, actorIds, faultStatus, count, size);
    }

}
